// 定义数据结构接口
interface IUser {
  nickname: string;
  avatarUrl: string;
  gender: 1 | 2; // 1: male, 2: female
  school: string;
  campus: string;
  phone: string; // 新增联系电话
}

interface IRecord {
  id: number;
  user: IUser;
  itemName: string;
  category: string;
  quantity: number;
  remark: string | null;
  createTime: string;
}

interface IQuickReply {
  text: string;
  selected: boolean;
}

Page({
  data: {
    records: [] as IRecord[],
    showModal: false,
    modalTitle: '',
    modalInputValue: '',
    quickReplies: [] as IQuickReply[],
    commonQuickReplies: {
      process: [
        { text: '已安排发货', selected: false },
        { text: '请耐心等待', selected: false },
        { text: '线下自提请联系', selected: false },
      ],
      reject: [
        { text: '库存不足', selected: false },
        { text: '信息不完整', selected: false },
        { text: '不满足条件', selected: false },
        { text: '恶意兑换', selected: false },
      ]
    },
    currentRecordIndex: -1,
    currentActionType: 'process' as 'process' | 'reject',
    submitting: false,
  },

  onLoad() {
    this.fetchRecords();
  },

  fetchRecords() {
    wx.showLoading({ title: '加载中...' });
    setTimeout(() => {
      const mockData: IRecord[] = [
        {
          id: 1001,
          user: { nickname: '追风的少年', avatarUrl: 'https://img.yzcdn.cn/vant/cat.jpeg', gender: 1, school: '数字科技大学', campus: '主校区', phone: '13800138000' },
          itemName: '限定版纪念T恤', category: '服饰', quantity: 1, remark: '希望能快点发货，谢谢！', createTime: '2023-10-26 10:00'
        },
        {
          id: 1002,
          user: { nickname: '向阳而生', avatarUrl: 'https://img.yzcdn.cn/vant/cat.jpeg', gender: 2, school: '数字科技大学', campus: '东校区', phone: '13900139000' },
          itemName: '定制版帆布袋', category: '周边', quantity: 2, remark: null, createTime: '2023-10-26 09:30'
        }
      ];
      this.setData({ records: mockData });
      wx.hideLoading();
    }, 1000);
  },

  /**
   * 新增：处理 "联系" 按钮点击事件
   */
  handleContact(event: WechatMiniprogram.TouchEvent) {
    const { phone } = event.currentTarget.dataset;
    if (phone) {
      this.showToast('联系');
    } else {
      this.showToast('未提供联系方式');
    }
  },

  handleAction(event: WechatMiniprogram.TouchEvent) {
    const { type, index } = event.currentTarget.dataset as { type: 'process' | 'reject', index: number };
    const replies = type === 'process'
      ? this.data.commonQuickReplies.process
      : this.data.commonQuickReplies.reject;

    this.setData({
      showModal: true,
      currentActionType: type,
      currentRecordIndex: index,
      modalTitle: type === 'process' ? '确认处理' : '确认驳回',
      quickReplies: JSON.parse(JSON.stringify(replies))
    });
  },

  closeModal() {
    this.setData({
      showModal: false,
      modalInputValue: '',
      submitting: false,
    });
  },

  onModalInput(event: WechatMiniprogram.Input) {
    this.setData({ modalInputValue: event.detail.value });
  },

  onSelectQuickReply(event: WechatMiniprogram.TouchEvent) {
    const { index } = event.currentTarget.dataset;
    const quickReplies = this.data.quickReplies as IQuickReply[];

    quickReplies[index].selected = !quickReplies[index].selected;

    const selectedTexts = quickReplies
      .filter(reply => reply.selected)
      .map(reply => reply.text)
      .join('，');

    this.setData({
      quickReplies,
      modalInputValue: selectedTexts,
    });
  },

  onModalConfirm() {
    if (this.data.submitting) return;

    this.setData({ submitting: true });

    const { currentRecordIndex, currentActionType, modalInputValue, records } = this.data;
    const recordToProcess = records[currentRecordIndex];

    console.log(`准备提交...`);
    console.log(`操作类型: ${currentActionType}`);
    console.log(`处理的记录ID: ${recordToProcess.id}`);
    console.log(`填写的原因/备注: ${modalInputValue}`);

    setTimeout(() => {
      this.showToast(`${this.data.modalTitle}成功`);

      const newRecords = [...this.data.records];
      newRecords.splice(currentRecordIndex, 1);

      this.setData({ records: newRecords });
      this.closeModal();
    }, 1500);
  },

  showToast(title: string) {
    wx.showToast({
      title: title,
      icon: 'none',
      duration: 2000
    });
  }
});